<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/14
 * Time: 10:24
 */
require_once './Redis.php';
$redis = new Rediss();
$server = new Swoole\Http\Server('0.0.0.0', 9502);
$server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
    $response->header('Access-Control-Allow-Origin', '*');
    $data = $request->post;
    $res = '';
    if (isset($data['nickname'])) { //注册模块
        $res = register($data);
    } else { //登录模块
        $res = login($data);
    }
    $response->end($res);//返回数据
});
$server->start();


function register($data)
{
    global $redis;
    $res = $redis->get('user_'.$data['name']);
    if ($res) {
        return error('账户已存在');
    }
    if ($redis->set('user_'.$data['name'],$data)) {
        return success('注册成功');
    }
}

function login($data)
{
    global $redis;
    $res = $redis->get('user_'.$data['name']);
    if (empty($res)) {
        return error('账户不存在');
    }
    if ($res['pass']!=$data['pass']) {
        return error('密码错误');
    }
    $token = md5(time());
    $tokenData =['username'=>$res['name'],'nickname'=>$res['nickname']];
    $redis->set('token_'.$token,$tokenData,3600);
    return success('登录成功',['token'=>$token]);
}


//制定返回格式 成功
function success($msg, $data = [])
{
    $datas = ['status' => 10000, 'msg' => $msg, 'data' => $data];
    return json_encode($datas);
}

//失败
function error($msg, $data = [])
{
    $datas = ['status' => 999, 'msg' => $msg, 'data' => $data];
    return json_encode($datas);
}